// pages/invoicedetails/invoicedetails.js
import api from "../../utils/api";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    coId: '',
    unitId: '',
    depId: '', //登录人部门id
    uuid: '',
    id: '',
    cancelid: '',
    invDate: '',
    idto: '',
    createAt: '',
    detailList: '',
    passed_active: 0,
    tax: '', //税款
    cusBankAccount: '', //银行卡号
    date: '', //日期
    invFormContentList: [], //任务号分摊数组
    is_cpyjf: '0', // 产品已交付
    needContract: '', //是否关联合同
    cancelButton: '', //是否可以作废（只有申请人可以）
    editable: '', //是否可以编辑（只有申请人可以）
    isCancel: '', //是否能看作废详情
    cancelId: '', //作废id

    flowList: [], // 审批流程
    voidflowList: [], //作废审批流程
    zanwu: false,
    show: false, //作废原因弹框
    voidReason: '', //作废原因-类型
    dictKey: '', //类型对应的key
    dictValue02: '', // 原因
    showType: false,
    columns: [], //下拉选作废类型
    voidRes: '', //输入的作废原因
    issubmit: false, //是否提交
    showtab3: false, //作废审批流程
    isExaminer: '', //审批意见显示与否
    fdId: '', // 流程ID
    voidfdId: '', //作废流程ID
    //审批
    fixed: true,
    message: '',
    shenpishow: false,
    flowId: '', // 流程ID

    businessType: '', //业务类型
    businessTypeStr: '',

    //到款项id
    receiveId: '',
    dkClaimId: '',
    //备注
    remarks: '',

  },
  // 输入审批意见
  onshenpiInput() {
    this.setData({
      shenpishow: true
    })
  },
  //  关闭弹窗
  onshenpiClose() {
    this.setData({
      shenpishow: false
    })
  },
  onshenpiChange(e) {
    this.setData({
      message: e.detail
    })
  },
  // 拒绝
  onDecline() {
    let that = this;
    api.jujue({
      data: {
        invId: that.data.id,
        flowId: that.data.flowId,
        flowNotes: that.data.message,
        userId: that.data.unitId
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '审批成功',
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 100);
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })
  },
  // 同意
  onAgree() {
    let that = this;
    api.tongyi({
      data: {
        invId: that.data.id,
        flowId: that.data.flowId,
        flowNotes: that.data.message,
        userId: that.data.unitId
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '审批成功',
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 100);
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })
  },
  formatDate(date) {
    //转时间戳
    date = new Date(date);
    return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  },
  //编辑
  edit() {
    wx.navigateTo({
      url: '/pages/editinvoice/editinvoice?id= ' + this.data.idto + '&needContract=' + this.data.needContract
    })
  },
  //查看作废详情
  voidDetails() {
    wx.navigateTo({
      url: '/pages/voidDetails/voidDetails?id= ' + this.data.cancelId
    })
  },
  //补充信息跳转
  buchong(e) {
    wx.navigateTo({
      url: '/pages/suppInformation/suppInformation?id= ' + this.data.id + '&code=' + this.data.detailList.code + '&deptName=' + this.data.userDept.deptName + '&userName=' + this.data.userDept.userName + '&from=' + e.currentTarget.dataset.from + '&receiveId=' + this.data.receiveId + '&dkClaimId=' + this.data.dkClaimId + '&invCode=' + this.data.detailList.invCode + '&voucherCode=' + this.data.detailList.voucherCode + '&voucherDate=' + this.data.detailList.voucherDate + '&voucherOp=' + this.data.detailList.voucherOp
    })
    // 部门opDeptId == 登录人id ?  是 可以补充  不是不能补充
    //  if( this.data.opDeptId == this.data.depId ){
    //  wx.navigateTo({
    //   url: '/pages/suppInformation/suppInformation?id= ' + this.data.id  + '&code=' + this.data.detailList.code  + '&deptName=' + this.data.userDept.deptName  + '&userName=' + this.data.userDept.userName  + '&from=' + e.currentTarget.dataset.from
    // })
    //  }else{
    //   wx.showModal({
    //     content: '您不是本部门人员，暂时还不可以查看哦~',
    //     showCancel: false,
    //     confirmColor: '#0041C4'
    //   })
    //  }
  },
  //复制发票
  copy() {
    let that = this;
    api.invCopy({
      method: 'POST',
      data: {
        invId: this.data.idto,
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: res.data.message,
          })
        }
      }
    })
  },
  //开票内容总金额
  sumMoneyByInvId() {
    let that = this;
    api.sumMoneyByInvId({
      data: {
        invId: this.data.id,
      },
      success: function (res) {
        if (res.data.code == 200) {
          that.setData({
            total: res.data.data
          })
        }
      }
    })
  },

  //点击  跳转到开票内容详情
  clickItem(e) {
    wx.navigateTo({
      url: '/pages/invContdetails/invContdetails?id= ' + e.currentTarget.dataset.id,
    })
  },
  //点击  跳转到合同详情
  clickItemcon(e) {
    wx.navigateTo({
      url: '/pages/taskNumdetails/taskNumdetails?id= ' + e.currentTarget.dataset.id,
    })
  },
  //点击  跳转到任务号详情
  clickrenwuhao(e) {
    wx.navigateTo({
      url: '/pages/taskNumdetails/taskNumdetails?id= ' + e.currentTarget.dataset.id,
    })
  },

  // 作废 -- 显示作废原因弹框
  void() {
    this.setData({
      show: true
    });
  },
  revoid() {
    wx.showToast({
      title: '请勿重复提交',
      icon: 'error'
    })
  },
  //作废原因-类型
  onviodType(event) {
    this.setData({
      showType: true
    });
    this.voidReason()

  },
  //作废原因类型列表初始渲染
  voidReason() {
    let that = this;
    api.getCancelReasonTypeList({
      data: {
        coId: that.data.coId,
      },
      success: function (res) {
        if (res.data.code = 200) {
          that.data.columns = [];
          if (res.data.data.length > 0) {
            res.data.data.forEach((item) => {
              let obj = {
                text: item.dictValue,
                dictKey: item.dictKey,
                dictValue02: item.dictValue02,
              }
              that.data.columns.push(obj)
            });
            that.setData({
              columns: that.data.columns,
            })
            that.setData({
              showType: true
            })
          } else {
            that.setData({
              showType: false
            })
          }

        }
      }
    })
  },
  onCancelType() {
    this.setData({
      showType: false
    });
  },
  onConfirmType(e) {
    const {
      value,
    } = e.detail;
    let text = value.text;
    let dictKey = value.dictKey;
    let dictValue02 = value.dictValue02;
    this.data.dictKey = dictKey;
    this.data.dictValue02 = dictValue02;
    this.setData({
      voidRes: this.data.dictValue02,
      voidReason: value.text,
      showType: false,
    })
  },
  //作废原因 输入
  onviodChange(event) {
    this.setData({
      voidRes: event.detail
    })
  },
  //作废原因 提交
  voidresSubmit() {
    let nowate = new Date();
    this.onClose()

    if (this.data.dictKey && this.data.voidRes) {
      let that = this;
      api.voidresSubmit({
        method: 'post',
        data: {
          invId: this.data.id,
          reason: this.data.voidRes,
          userId: this.data.unitId,
          invDate: this.data.createAt,
          cancelReasonType: this.data.dictKey,
          cancelledDate: new Date().getTime()
        },
        success: function (res) {
          if (res.data.code == 200) {
            if (res.data.data == null) {
              wx.showToast({
                title: '作废已提交',
              })
              that.getDate()
              that.setData({
                showtab3: true,
                passed_active: 1
              });
            } else {
              that.data.cancelid = res.data.data
              that.setData({
                issubmit: true,
                // cancelid: res.data.data
              })
              wx.navigateTo({
                url: '/pages/voidDetails/voidDetails?id= ' + that.data.cancelid,
              })
            }
          }
        }
      })
    } else {
      wx.showToast({
        title: '作废类型,作废原因是必填项哦~',
        icon: 'none'
      })
    }
  },
  //关闭作废原因弹框
  onClose() {
    this.setData({
      show: false
    });
  },
  //切换选项卡
  onChange(event) {
    if (event.detail.index == 1) {
      this.invProcess()
    } else {
      this.voidinvProcess()
    }
  },
  //审批流程
  invProcess() {
    let that = this;
    api.invProcess({
      data: {
        uuid: this.data.uuid
      },
      success: function (res) {
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].flowStepStatus == null) {
              that.data.flowId = res.data.data[i].flowId
            }
          }
          if (res.data.data.length > 0) {
            that.setData({
              flowList: res.data.data,
              flowId: that.data.flowId
            })
          } else {
            that.setData({
              zanwu: true
            })
          }

        }
      }
    })
  },
  //作废审批流程
  voidinvProcess() {
    let that = this;
    api.voidinvProcess({
      data: {
        uuid: this.data.uuid
      },
      success: function (res) {
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].flowStepStatus == null) {
              that.data.voidfdId = res.data.data[i].flowId
            }
          }
          if (res.data.data.length > 0) {
            that.setData({
              voidflowList: res.data.data,
              voidfdId: that.data.flowId
            })
          } else {
            that.setData({
              zanwu: true
            })
          }

        }
      }
    })
  },
  addComma(date) {
    let str = '';
    let num = '';
    let newStr = '';
    date = date + '';
    if (date.indexOf('.') != -1) {
      num = date.split('.')[0]
      str = date.split('.')[1]
    } else {
      num = date
    }
    newStr = num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    newStr = str == '' ? newStr : newStr + '.' + str;
    return newStr;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //获取详情页数据
  getDate() {
    let that = this;
    api.invDetails({
      data: {
        id: this.data.id,
      },
      success: function (res) {
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.sysDictContractList.length; i++) {
            res.data.data.sysDictContractList[i].money = that.addComma(res.data.data.sysDictContractList[i].money)
            res.data.data.sysDictContractList[i].waitMoney = that.addComma(res.data.data.sysDictContractList[i].waitMoney)
          }
          for (let i = 0; i < res.data.data.invFormContentList.length; i++) {
            res.data.data.invFormContentList[i].money = that.addComma(res.data.data.invFormContentList[i].money)
          }
          for (let i = 0; i < res.data.data.invTaskList.length; i++) {
            res.data.data.invTaskList[i].money = that.addComma(res.data.data.invTaskList[i].money)
          }
          //往来单位
          for (let i = 0; i < res.data.data.sysDictCustomer.length; i++) {
            // console.log(typeof(res.data.data.sysDictCustomer[i].bankAccount)) 
          }
          res.data.data.money = that.addComma(res.data.data.money)
          that.setData({
            word: this.data.typeValue,
            coId: res.data.data.coId,
            uuid: res.data.data.uuid,
            detailList: res.data.data,
            userDept: res.data.data.userDept,
            tax: res.data.data.money * res.data.data.taxRate,
            date: res.data.data.receiveDate ? that.formatDate(res.data.data.receiveDate) : '',
            // needContract:res.data.data.needContract,
            sysDictContractList: res.data.data.sysDictContractList,
            sysDictCustomer: res.data.data.sysDictCustomer,
            idto: res.data.data.id,
            createAt: res.data.data.createAt,
            isExaminer: res.data.data.isExaminer,
            is_cpyjf: res.data.data.is_cpyjf, // 产品已交付
            needContract: res.data.data.needContract, //是否关联合同
            cancelButton: res.data.data.cancelButton, // 是否是审批人（能否作废）
            editable: res.data.data.editable, // 是否编辑（能否作废）
            isCancel: res.data.data.isCancel, //是否能看作废详情
            cancelId: res.data.data.cancelId, //作废id
            opDeptId: res.data.data.opDeptId, //部门id
            businessTypeStr: res.data.data.businessTypeStr,
            businessType: res.data.data.businessType, //业务类型
            isCopy: res.data.data.isCopy, //发票是否能复制
            noContractReason: res.data.data.noContractReason, //无合同原因
            receiveId: res.data.data.receiveId, //到款项id
            dkClaimId: res.data.data.dkClaimId,
            remarks: res.data.data.remarks, //备注
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.unitId = wx.getStorageSync('userInfo').unitId
    this.data.depId = wx.getStorageSync('userInfo').depId, //登录人的部门id

      this.getDate()
    this.sumMoneyByInvId()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})